package com.mes.cloud.base.Aspect;

import com.mes.cloud.commons.CommonError;
import com.mes.cloud.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 校验用户是否登录
 * Created by pact on 2018/7/10.
 */
/*@Aspect
@Component*/
public class LoginValidatorAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginValidatorAspect.class);

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 对客户端的请求进行校验
     * 查看当前登录用户是否有权限调用接口
     * @param joinPoint
     * @return
     */
    @Around("within(com.mes.cloud.*.controller..*)")
    public Object Authorize(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        // 获取token参数并校验
        String apiToken = request.getParameter("token");
        if (request == null || apiToken == null) {
            return CommonError.PARAM_IS_NULL.toJSONResult("HttpServletRequest");
        }
        Object result = null;
        try {
            // 拦截非登录请求并验证token是否存在
            Boolean haskey = redisTemplate.hasKey(apiToken);
            if (!haskey) {
                return CommonError.LOGIN_TIMEOUT.toJSONResult("HttpServletRequest");
            }
            result = joinPoint.proceed();
        } catch (Throwable throwable) {
            return CommonError.FAIL_ERROR.toJSONResult("服务异常");
        }
        return result;
    }
}
